import { Module } from 'vuex'
import { v4 as uuidv4 } from 'uuid'
import { GlobalDataProps } from './index'
import { TextComponentProps } from '../defaultProps'
import { remove } from 'lodash-es'
export interface ComponentsData {
  props: { [key: string]: any };
  id: string;
  name: string;
}

/**
 * 整个编辑的状态
 */
export interface EditorGlobalData {
  //画布要渲染的集合
  component: ComponentsData[];
  //当前编辑的元素
  currentComponent: string;
}

export const testData: ComponentsData[] = [
  { id: uuidv4(), name: 'l-text', props: { text: 'hello', fontSize: "16px", color: 'red', lineHeight: "1", textAlign: 'left', fontFamily: '"SimSun","STsong"',fongWeight:"normal", } },
  { id: uuidv4(), name: 'l-text', props: { text: 'hello2', "fontSize": "12px" } },
  { id: uuidv4(), name: 'l-text', props: { text: 'hello3', "fontSize": "24px", actionType: 'url', url: "https://www.baidu.com" } }
]

const editor: Module<EditorGlobalData, GlobalDataProps> = {
  state: {
    component: testData,
    currentComponent: ''
  },
  //mutations:相当于vuex 的事件方法，这里可以同步进行更新state的值
  mutations: {
    /**
     * 为画布中添加元素
     * @param state 
     * @param props 
     */
    addComponent(state, props: Partial<TextComponentProps>) {
      const newComponent: ComponentsData = {
        id: uuidv4(),
        name: 'l-text',
        props
      }
      state.component.push(newComponent)
    },
    /**
     * 删除画布中元素
     * @param state 
     * @param props 
     */
    delComponent(state, currentId: string) {
      state.component = remove(state.component, (item) => {
        return item.id !== currentId
      })
    },
    /**
     * 设置当前选择的的画布元素的ID
     * @param state 
     * @param currentId 元素ID
     */
    setActive(state, currentId: string) {
      state.currentComponent = currentId
    },
    /**
     * 更新当前选中的画布数据
     * @param state 
     * @param {key,value} key,value
     */
    updateComponent(state, { key, value }) {
      const updateComponent = state.component.find(component => component.id === state.currentComponent)
      if (updateComponent) {
        updateComponent.props[key as keyof TextComponentProps] = value
      }

    }
  },
  //getter:相当于是vuex的计算属性，它内部可以处理state数据的更新返回一个组件需要的值，使得组件不直接操作vuex数据
  getters: {
    getCurrentElement: (state) => {
      return state.component.find(component => component.id === state.currentComponent)
    }
  }
}

export default editor